import java.util.Random;

/**
 * 模拟退火算法工具类
 * ======================================
 * USER NAME: ving <904679843@qq.com>
 * DATE TIME: 17-9-12 下午8:14
 * ======================================
 */
 public class SATool{

    /**
     * 随机生成路径
     * @param length  生成路径的场长度
     * @param head    生成路径的第一个数
     * @return        放回以length长度，以head开始的路径数组
     */
     public static int[] shufflePath(int length, int head){
         Random random = new Random();

         int i, j;
         int[] path = new int[length];
         path[0] = head;

         for (i = 1; i < length; ) {
             path[i] = random.nextInt(Integer.MAX_VALUE) % length;
             for (j = 0; j < i; j++) {
                 if (path[i] == path[j]) {
                     break;
                 }
             }
             if (j == i) {
                 i++;
             }
         }

         return  path;
     }

    /**
     * 将老的路径数组随机交换两个位置在复制给新的路径
     * @param oldPath  老的路径
     * @param newPath  新的路径
     * @return         返回新的路径
     */
     public static int[] shuffleChangeOldPathToNewPath(int[] oldPath, int[] newPath){
         Random random = new Random();

         int ranOne = 0;
         int ranTwo = 0;
         int length = oldPath.length;

         copyPath(oldPath,newPath);

         while (ranOne == ranTwo || ranOne == 0 || ranTwo == 0) {
             ranOne = random.nextInt(Integer.MAX_VALUE) % length;
             ranTwo = random.nextInt(Integer.MAX_VALUE) % length;
         }

         swapPathPosition(newPath,ranOne,ranTwo);

         return newPath;
     }

    /**
     * 继续路径的总路长
     * @param distance  距离矩阵
     * @param path      路径数组
     * @return          返回以path的路径的总路长
     */
    public static int calculatePathLength(double[][] distance,int[] path){
        int length = path.length;
        int pathLength = 0;

        for (int i = 0; i < length; i++) {
            int x = path[i % length];
            int y = path[(i + 1) % length];

            if (distance[x][y] == -1){
                return Integer.MAX_VALUE;
            }else{
                pathLength += distance[x][y];
            }

        }

        return pathLength;
    }

    /**
     * 将路径pathOne复制给pathTwo
     * @param pathOne
     * @param pathTwo
     */
    public static void copyPath(int[] pathOne, int[] pathTwo){
         System.arraycopy(pathOne, 0, pathTwo, 0, pathTwo.length);
    }

    /**
     * 交换路径数组中的x和y的位置
     * @param path
     * @param x
     * @param y
     * @return
     */
    public static int[] swapPathPosition(int[] path, int x, int y) {
        int temp = path[x];
        path[x] = path[y];
        path[y] = temp;
        return path;
    }
}